package com.srlg.conf;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.inject.Inject;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.ExceptionMapper;
import jakarta.ws.rs.ext.Provider;
import lombok.extern.slf4j.Slf4j;

/**
 * @desc:
 * @author: srlg li
 * @date: 2024/12/30 上午12:01
 */
@Provider
@Slf4j
public class ErrorMapper implements ExceptionMapper<Exception> {

    @Inject
    ObjectMapper objectMapper;

    @Override
    public Response toResponse(Exception e) {
        log.error("Failed to handle request", e);

        int code = 500;
        if (e instanceof WebApplicationException we) {
            code = we.getResponse().getStatus();
        }

        ObjectNode expJson = objectMapper.createObjectNode();
        expJson.put("exceptionType", e.getClass().getName());
        expJson.put("code", code);

        if (e.getMessage() != null) {
            expJson.put("error", e.getMessage());
        }

        return Response.status(code).entity(expJson).build();
    }
}
